package org.yoao.crm.business.impl;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.yoao.crm.bean.StaticBean;
import org.yoao.crm.business.service.ISMSService;
import org.yoao.crm.dao.CustomerDAO;
import org.yoao.crm.sms.SMSSender;
import org.yoao.crm.struts.form.SmsForm;
import org.yoao.crm.tools.FileTool;

import com.nineorange.service.BusinessService;

/**
 * @author yxwonline.com
 * @description
 * @date 2010-8-5 下午04:40:55
 */
public class SMSServiceImpl implements ISMSService {

	private static String smsPath = SMSServiceImpl.class.getResource("/") + "resources/sms.properties";

	public SMSServiceImpl(){
		if(smsPath != null && smsPath.startsWith("file:/")) smsPath = smsPath.substring(6);
		FileTool fileTool = new FileTool(smsPath);
		if(!fileTool.exists()){
			fileTool.create();
		}
	}

	@Override
	public String[] init() throws Exception {
		Properties property = new Properties();
		property.clear();
		InputStream in = new BufferedInputStream(new FileInputStream(smsPath));
		property.load(in);
		in.close();
		String[] result = {
							property.getProperty(StaticBean.SMSSERVERADDRESS),
							property.getProperty(StaticBean.SMSUSER),
							property.getProperty(StaticBean.SMSPASSWORD),
							property.getProperty(StaticBean.SMSCONTENTNAME)
						  };
		return result;
	}

	@Override
	public String[] save(SmsForm form) throws Exception {
		Properties property = new Properties();
		FileInputStream in = new FileInputStream(smsPath);
		property.load(in);
		in.close();

		property.setProperty(StaticBean.SMSSERVERADDRESS, form.getServer());
		property.setProperty(StaticBean.SMSUSER, form.getUser());
		property.setProperty(StaticBean.SMSPASSWORD, form.getPassWord());
		property.setProperty(StaticBean.SMSCONTENTNAME, form.getContent());

		FileOutputStream out = new FileOutputStream(smsPath);
		property.store(out, null);
		out.flush();
		out.close();

		String[] result = {form.getServer(), form.getUser(), form.getPassWord(), form.getContent()};
		return result;
	}

	/**
	 * 发送短信
	 */
	public String send(String id) throws Exception {
		List mobileList = new CustomerDAO().findAllMobile(id);
		if (mobileList == null || mobileList.isEmpty())
			return "未获取到需要发送短信的手机号.";
		int size = mobileList.size();
		StringBuffer mobiles = new StringBuffer();
		for(int i = 0; i < size; i++){
			mobiles.append(mobileList.get(i) + ",");
		}
		String[] mobileArray = mobiles.toString().split(",");
		List receiveList = new ArrayList();
		StringBuffer signleTimeMobile = new StringBuffer();
		int count = 0;
		for(int i=0;i<mobileArray.length;i++){
			count++;
			if(count > 1000){
				count = 0;
				signleTimeMobile = new StringBuffer();
				receiveList.add(signleTimeMobile);
			}
			signleTimeMobile.append(mobileArray[i]);
		}
		
		Properties property = new Properties();
		property.clear();
		InputStream in = new BufferedInputStream(new FileInputStream(smsPath));
		property.load(in);
		in.close();
		String server = property.getProperty(StaticBean.SMSSERVERADDRESS);
		String user = property.getProperty(StaticBean.SMSUSER);
		String passWord = property.getProperty(StaticBean.SMSPASSWORD);
		String content = property.getProperty(StaticBean.SMSCONTENTNAME);
		String time = "";

		return sender(receiveList, server, user, passWord, content, time);
	}

	private String sender(List mobiles, String server, String user, String passWord, String content, String time) throws Exception{
		StringBuffer result = new StringBuffer();
		SMSSender  smsSender = new SMSSender();
		for(int i=0;i<mobiles.size();i++){
			String r = smsSender.sendSMS(server, user, passWord, mobiles.get(i).toString(), content, time);
			if(r != null && ("000".equals(r) || r.length() > 4))
				result.append("短信发送到"+mobiles.get(i).toString()+"成功.");
			else if("-01".equals(r))
				result.append("账户余额不足.");
			else if("-02".equals(r))
				result.append("帐号错误.");
			else if("-03".equals(r))
				result.append("密码错误.");
			else if("-04".equals(r))
				result.append("参数不够或参数内容的类型错误.");
			else if("-05".equals(r))
				result.append("手机号码格式不对.");
			else if("-06".equals(r))
				result.append("短信内容编码不对.");
			else if("-07".equals(r))
				result.append("短信内容含有敏感字符.");
			else if("-08".equals(r))
				result.append("无接收数据.");
			else if("-09".equals(r))
				result.append("系统维护中.");
			else if("-10".equals(r))
				result.append("手机号码数量超长.");
			else if("-11".equals(r))
				result.append("短信内容超长！（70个字符）.");
			else if("-12".equals(r))
				result.append("其它错误.");
			else if("-13".equals(r))
				result.append("文件传输错误.");
			else
				result.append("未知返回参数:"+r+",请与短信平台服务商联系.");
		}
		return result.toString();
	}

	private String sender(List mobiles, String server, String user, String passWord, String content) throws Exception{
		StringBuffer result = new StringBuffer();
		BusinessService sender = new BusinessService();
		sender.setWebService(server);
		for(int i=0;i<mobiles.size();i++){
			int r = sender.sendBatchMessage(user, passWord, mobiles.get(i).toString(), content);
			if(r > 0)
				result.append("短信发送到"+mobiles.get(i).toString()+"成功.");
			else if(r == -1)
				result.append("账户余额不足.");
			else if(r == -2)
				result.append("帐号或密码错误.");
			else if(r == -3)
				result.append("连接服务商失败.");
			else if(r == -4)
				result.append("和服务器连接超时.");
			else if(r == -5)
				result.append("其他错误.");
			else if(r == -6)
				result.append("短信内容为空.");
			else if(r == -7)
				result.append("目标号码为空.");
			else if(r == -8)
				result.append("用户通道设置不对，需要设置三个通道.");
			else if(r == -9)
				result.append("捕获未知异常.");
			else if(r == -10)
				result.append("超过最大定时时间限制.");
			else if(r == -11)
				result.append("目标号码在黑名单里.");
			else if(r == -12)
				result.append("消息内容包含禁用词语.");
			else if(r == -13)
				result.append("没有权限使用该网关.");
			else if(r == -14)
				result.append("找不到对应的Channel ID.");
			else
				result.append("未知返回参数:"+r+",请与短信平台服务商联系.");
		}
		return result.toString();
	}
}
